package com.cskaoyan.order.biz.handler;

import com.alibaba.fastjson.JSON;
import com.cskaoyan.mall.commons.constant.SysRetCodeConstants;
import com.cskaoyan.mall.commons.exception.BaseBusinessException;
import com.cskaoyan.mall.commons.exception.BizException;
import com.cskaoyan.order.biz.context.AbsTransHandlerContext;
import com.cskaoyan.order.biz.context.CreateOrderContext;
import com.cskaoyan.order.biz.context.TransHandlerContext;
import com.cskaoyan.order.dal.entitys.Stock;
import com.cskaoyan.order.dal.persistence.StockMapper;
import com.cskaoyan.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @Description: 扣减库存处理器
 **/
@Component
@Slf4j
public class SubStockHandler extends AbstractTransHandler {

    @Autowired
    private StockMapper stockMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
    @Transactional
    public boolean handle(TransHandlerContext context) {
        // 向下转型
        CreateOrderContext createOrderContext = ((CreateOrderContext) context);
        // 获得请求参数中购物车的商品列表
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        // 获得商品id的列表
        List<Long> productIds = createOrderContext.getBuyProductIds();
        if (CollectionUtils.isEmpty(productIds)) {
            for (CartProductDto cartProductDto : cartProductDtoList) {
                productIds.add(cartProductDto.getProductId());
            }
        }
        // 根据商品id获取库存信息
        List<Stock> stocks = stockMapper.findStocksForUpdate(productIds);
        // 如果库存列表为空或者小于商品列表数目，说明有部分商品库存没有在表中
        if (CollectionUtils.isEmpty(stocks) || (stocks.size() != productIds.size())) {
            throw new BizException(SysRetCodeConstants.DATA_NOT_EXIST.getCode(), "商品库存未初始化！");
        }
        // 可售卖库存减少，冻结库存增加，注意不要超过限购
        for (CartProductDto cartProductDto : cartProductDtoList) {
            Long productId = cartProductDto.getProductId();
            Long productNum = cartProductDto.getProductNum();
            // 根据商品id查找对应库存信息
            Stock stock = stockMapper.selectStockForUpdate(productId);
            // 如果购买数量超过限购数量，抛异常
            if (productNum.intValue() > stock.getRestrictCount()) {
                throw new BizException(SysRetCodeConstants.REQUEST_DATA_ERROR.getCode(), "购买数量超过限购数量！");
            }
            // 更新库存
            stock.setLockCount(productNum.intValue());
            stock.setStockCount(-productNum);
            stockMapper.updateStock(stock);
        }

        return true;
    }
}